package com.cac.demo.util;

import com.cac.demo.dao.gkLog.MsAddressDao;
import com.cac.demo.dao.gkLog.WcsLogRecordDao;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.cac.demo.newCode.materialStorage.service.IMsSslShelvesService;
import com.cac.demo.util.adapter.ComUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class WcsLogRecord {
    @Autowired
    private Environment environment;
    @Autowired
    private WcsLogRecordDao wcsLogRecordDao;
    @Autowired
    private MsAddressDao msAddressDao;

    /**
     * 只记录wcs回调，调用callBack
     * 记录日志wcs调用日志
     * isCheck:是否校验此处推送
     * 该方法不管原来事务是否存在都创建一个新的事务，此事务执行完毕后在执行原来的事务
     **/
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public HashMap saveCallBackLog(Map map, Map extendMap, boolean isCheck, String wmsTaskId) {
        HashMap retMap = new HashMap();
        try {
            String opWcsLog = environment.getProperty("pathProperty.opWcsLog");
            if ("false".equals(opWcsLog)) {//是否开启日志记录
                retMap.put("retCode", "1");
                return retMap;
            }
            //查询是否调用过记录是否成功
//            String wmsTaskId = map.get("wmsTaskId").toString();
            if (isCheck) {//校验此处推送是否已经推送过
                if (!"2".equals(map.get("command").toString())) {
                    retMap.put("retCode", "1");
                } else {
                    int cnt = wcsLogRecordDao.queryTaskExists(wmsTaskId, map.get("command").toString());
                    if (cnt == 0) {//wms未收到此消息
                        retMap.put("retCode", "1");
                    } else {//wms已经收到此消息
                        retMap.put("retCode", "0");
                    }
                }
            } else {//不校验
                retMap.put("retCode", "1");
            }
            HashMap logMap = new HashMap();
            logMap.put("taskId", wmsTaskId);
            logMap.put("command", map.get("command"));
            logMap.put("palletCode", map.get("palletCode"));
            logMap.put("param", map.toString());
            logMap.putAll(extendMap);
            wcsLogRecordDao.insertWcsLog(logMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retMap;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateDeatilLog(Map extendMap) {
        try {
            HashMap logMap = new HashMap();
            logMap.putAll(extendMap);
            wcsLogRecordDao.updateDetailLog(logMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateLog(Map extendMap) {
        HashMap logMap = new HashMap();
        logMap.putAll(extendMap);
        wcsLogRecordDao.updateLog(logMap);
    }


    //获取wcs任务
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String dealWmsUnFinishTask(String palletCode) {
        try {
            String wmsTaskId = null;
            HashMap ret = wcsLogRecordDao.selectWmsTaskIdByPalletCode(palletCode);
            if (Objects.isNull(ret)) {
                log.info("wms不存在未完成任务【" + palletCode + "】");
                return "wms不存在未完成任务【" + palletCode + "】";
            } else {
                wmsTaskId = (String) ret.get("wmsTaskId");
                //查询wms任务是否完成，如果完成则不调用接口
                Map param = GetAuthKey.getKey();
                param.put("command", "3");
                param.put("wmsTaskId", wmsTaskId);
                String urlPath = msAddressDao.findPath("WCS");
                String jsonstr = JSON.toJSONString(param);
                urlPath += "/api/wcs/api/chengfei/task";
                String result = HttpUtil.post(urlPath, jsonstr);
                JSONObject jsonObject = JSON.parseObject(result);
                if ("200".equals(jsonObject.get("code"))) {
                    JSONObject retjson = jsonObject.getJSONObject("data");
                    log.info("");
                    if (!Objects.isNull(retjson)) {
                        if ("2".equals(retjson.get("status").toString())) {
                            //记录日志
                            HashMap logMap = new HashMap();
                            logMap.put("ID", ComUtil.getId());
                            logMap.put("taskId", wmsTaskId);
                            logMap.put("logType", "queryWcsTask");
                            logMap.put("command", 3);
                            logMap.put("wcsResult", result);
                            logMap.put("param", jsonstr);
                            wcsLogRecordDao.insertWcsLog(logMap);
                            //更新gk_log信息
                            wcsLogRecordDao.updateGkLogState((String) ret.get("msGkLogId"));
                            //缓存箱任务完成，发送到数字孪生
                            JSONObject json = new JSONObject();
                            json.put("boxCode", palletCode);
                            json.put("taskNo", wmsTaskId);
                            json.put("type", wmsTaskId);
                            String MqttUrl = environment.getProperty("lesApi.sendMqttMessage");
                            Map<String, String> sendData = new HashMap<>();
                            sendData.put("qos","1");
                            sendData.put("retained","false");
                            sendData.put("topic", "sendTaskInfo");
                            sendData.put("message",json.toJSONString());
                            com.cac.demo.util.HttpUtil.get(MqttUrl,sendData);
                            //yebo 根据wcs任务更改货架
                            if ("2".equals(retjson.get("taskType").toString())) {//taskType:1,入库，2：出库，3：移库
                                wcsLogRecordDao.dealShelves(palletCode, (String) retjson.get("startCode"));
                            } else if ("1".equals(retjson.get("taskType").toString())) {
                                wcsLogRecordDao.dealShelvesStatus(palletCode, (String) retjson.get("startCode"));
                            }
                        } else {
                            log.info("wcs任务未完成【" + palletCode + "】");
                            return "wcs任务未完成【" + palletCode + "】";
                        }
                    }
                } else {
                    log.info("调用wcs接口异常【" + palletCode + "】");
                    return "调用wcs接口异常【" + palletCode + "】";
                }

            }
            log.info("更改完毕【" + palletCode + "】");
            return "更改完毕【" + palletCode + "】";
        } catch (Exception e) {
            e.printStackTrace();
            log.info("wms处理异常【" + palletCode + "】");
            return "wms处理异常【" + palletCode + "】";
        }
    }

    //定时任务调用改方法
    //http://192.168.50.176:8080/ScheduledTask/sysDealSslShelves
    public String sysUnFinishTask(String palletCode, long systime) {
        try {
            String wmsTaskId = null;
            HashMap ret = wcsLogRecordDao.selectWmsTaskIdByPalletCode(palletCode);
            if (Objects.isNull(ret)) {
                log.info("wms没有不存在未完成任务【" + palletCode + "============】" + systime);
                return "wms没有不存在未完成任务【" + palletCode + "】";
            } else {
                wmsTaskId = (String) ret.get("wmsTaskId");
                //查询wms任务是否完成，如果完成则不调用接口
                Map param = GetAuthKey.getKey();
                param.put("command", "3");
                param.put("wmsTaskId", wmsTaskId);
                String urlPath = msAddressDao.findPath("WCS");
                urlPath += "/api/wcs/api/chengfei/task";
                String jsonstr = JSON.toJSONString(param);
                log.info("=====定时任务调用wcs参数======" + jsonstr);
                String result = HttpUtil.post(urlPath, jsonstr);
                log.info("======定时任务返回参数======"+result);
                JSONObject jsonObject = JSON.parseObject(result);
                if ("200".equals(jsonObject.get("code").toString())) {
                    try{
                        JSONObject retjson = jsonObject.getJSONObject("data");
                        if (!Objects.isNull(retjson)) {
                            if ("2".equals(retjson.get("status").toString())) {
                                //记录日志
                                HashMap logMap = new HashMap();
                                logMap.put("ID", ComUtil.getId());
                                logMap.put("taskId", wmsTaskId);
                                logMap.put("logType", "queryWcsTask");
                                logMap.put("command", 3);
                                logMap.put("wcsResult", result);
                                logMap.put("param", jsonstr);
                                wcsLogRecordDao.insertWcsLog(logMap);
                                //更新gk_log信息
                                wcsLogRecordDao.updateGkLogState((String) ret.get("msGkLogId"));
                                //yebo 根据wcs任务更改货架
                                if ("2".equals(retjson.get("taskType").toString())) {//taskType:1,入库，2：出库，3：移库
                                    wcsLogRecordDao.dealShelves(palletCode, (String) retjson.get("startCode"));
                                } else if ("1".equals(retjson.get("taskType").toString())) {
                                    wcsLogRecordDao.dealShelvesStatus(palletCode, (String) retjson.get("startCode"));
                                }
                            } else {
                                log.info("wcs任务未完成【" + palletCode + "】===============" + systime);
                                return "wcs任务未完成【" + palletCode + "】";
                            }
                        }
                    }catch (Exception ex){
                        ex.printStackTrace();
                        log.info("定时任务异常捕获，继续执行");
                    }
                } else {
                    log.info("调用wcs接口异常【" + palletCode + "】===================" + systime);
                    return "调用wcs接口异常【" + palletCode + "】";
                }

            }
            log.info("更改完毕【" + palletCode + "】===========" + systime);
            return "更改完毕【" + palletCode + "】";
        } catch (Exception e) {
            e.printStackTrace();
            log.info("wms处理异常【" + palletCode + "】==============" + systime);
            return "wms处理异常【" + palletCode + "】";
        }
    }
}
